/**
 * 
 * @authors youzhao.zhou@pandauu.com
 * @date    2016-10-19 12:38:09
 * @version $Id$
 */

;(function(root,factory){

  if(typeof exports === 'object' && typeof module === 'object'){
    
    factory(exports);

  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['exports'], factory);
  } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
    // CommonJS
    factory(exports);
  } else {
    // Browser globals
    if (!root._s) {
      root._s = {};
    }
    factory(root);
  }
})(typeof window !== 'undefined' ? window : this ,function(exports, undefined){
  'use strict';

  function moduleInit($, utils){

    var pubsub = utils.pubSub()||{};
    var callback = {};
    var callbackFuc = utils.callbackFuc;

    function init(identifier, callbacks){
      
      callback[identifier] = [callbacks];

      pubsub.addEvent(identifier, function(data){
        console.log(data);
        callbackFuc(callback[identifier],data);
      });

      return {
        set: function(identifier, options){
          receiver(identifier, options);
        }
      };
      
    }

    function receiver(identifier, options){

      switch(identifier){
        case 'imgDefer':
          imgDefer(identifier, options&&options.data);
        break;
        case 'imgOneDefer':
          imgOneDefer(identifier, options);
        break;
      }
      
    };
    /*
      图片延时加载
    */

    function imgDefer(identifier){
      var doms = $('[data-deferr]');

      doms.each(function(index, el) {

        if (parseInt(el.getAttribute('data-deferr')) != 1) {
          return false;
        }
        var self = this;
        var imgUrl = $(self).data('url');

        var img = new Image();

          img.onload = function(){

          $(self).attr({
            src : imgUrl
          });

          pubsub.fireEvent(identifier,{code:0,dom: self, img: img });

        };

        img.src = imgUrl;
      });

    }

    /*
      单张图片延时加载
    */
    function imgOneDefer(identifier,data){
      var dom = document.createElement('img');
      console.log(data);
      dom.onload = function(){

        $('[data-deferr="0"]')[0].src = data.msg;
        
        pubsub.fireEvent(identifier,{
          code: 0,
          dom: $('[data-deferr="0"]')[0],
          img: $('[data-deferr="0"]')[0]
        });
      };

      dom.src = data.msg;
    }

    return {
      receiver: init //接收通知
    };
  }


  exports.imgDefer = moduleInit;

});